window.onload = function() {
    const $ = name => document.querySelector(name);
    var token1 = window.localStorage.getItem('token');
    var logging = $('.logging');
    var mask = $('.wrapper');
    var loginbtn1 = document.getElementById('loginbtn1');
    var loginbtn2 = document.getElementById('loginbtn2');
    var loginbtn3 = document.getElementById('loginbtn3');
    var rlogo = document.getElementById('rlogo');
    var userinfo = document.getElementById('userinfo');
    var dropbtn = $('.dropdown');
    var teacherlogo = document.getElementById('teachercentre');
    axios.defaults.timeout = 5500;
    axios.defaults.baseURL = 'http://120.24.80.83:3000';
    // axios.defaults.headers.common['Authorization'] = token1;
    axios.interceptors.request.use(function(config) {
        // 在发送请求之前做些什么
        // 若token存在， 则在每次请求头中加入token
        if (window.localStorage.getItem('token')) {
            config.headers.Authorization = window.localStorage.getItem('token');
            // axios.defaults.headers.common['Authorization'] = window.localStorage.getItem('token');
        }
        // console.log(config);
        return config;
    }, function(error) {
        // 对请求错误做些什么
        return Promise.reject(error);
    });
    axios.interceptors.response.use(
            response => {
                if (getCookie("init")) {
                    var cookie = JSON.parse(getCookie("init"));
                } else {
                    var cookie = new Object();
                    var cookie = {
                        name: '',
                        pass: ''
                    };
                }
                if (response.data.msg == '登录失效' && (cookie.name == '' && cookie.pass == '')) {
                    // 这里写清除token的代码
                    // 清除token
                    console.log(response.data.msg);
                    setTimeout(() => {
                        // window.open('login.html');
                        loginbtn1.style.display = 'block';
                        loginbtn2.style.display = 'block';
                        loginbtn3.style.display = 'block';
                        rlogo.style.display = 'none';
                        userinfo.style.display = 'none';
                        userinfo.style.height = '0';
                    }, 3000);
                    // window.localStorage.removeItem('token');
                    console.log('登录过期，请重新登录');
                    Message({
                        message: '登录过期，请重新登录',
                        duration: 1000,
                        forbidClick: true
                    });
                    Message();
                    // window.location.href = 'login.html';
                } //else if ((response.data.code == 1 && (cookie.name != '' && cookie.pass != '')) || (response.data.code == 1 && (cookie.name == '' && cookie.pass == ''))) {
                //     console.log('登录状态');
                //     loginbtn1.style.display = 'none';
                //     loginbtn2.style.display = 'none';
                //     loginbtn3.style.display = 'none';
                //     rlogo.style.display = 'block'
                //     userinfo.style.display = 'block';
                //     if (window.localStorage.getItem('avatar')) {
                //         document.querySelector('#rlogo img').src = window.localStorage.getItem('avatar');
                //     }
                // }
                return response;
            },
            error => {
                if (error.response) {
                    switch (error.response.status) {
                        case 403:
                            // 这里写清除token的代码
                            console.log('清除token');
                            id1 = '';
                            Message({
                                message: '登录过期，请重新登录',
                                duration: 1000,
                                forbidClick: true
                            });
                            // 清除token
                            window.loaclStorage.removeItem('token');
                            // store.commit('loginSuccess', null);
                            // 跳转登录页面，并将要浏览的页面fullPath传过去，登录成功后跳转需要访问的页面
                            // setTimeout(() => {
                            //     router.replace({
                            //         path: '/login',
                            //         query: {
                            //             redirect: router.currentRoute.fullPath
                            //         }
                            //     });
                            // }, 1000);
                            break;
                    }
                }
                return Promise.reject(error.response.data)
            }
        )
        //页面加载时，如果有记录7天免登录
    if (getCookie("init")) {
        var cookie = JSON.parse(getCookie("init"));
        if (cookie.name != '' && cookie.pass != '') {
            axios({
                    url: "/login",
                    method: "post",
                    data: {
                        "username": cookie.name,
                        "password": cookie.pass,
                    }
                })
                .then(function(response) {
                    console.log(response.data);
                    var res = response.data.data;
                    //使用loackstorge保存token，方便以后需要的时候用
                    personBusi();
                    window.localStorage.setItem("token", res.token);
                    loginbtn1.style.display = 'none';
                    loginbtn2.style.display = 'none';
                    loginbtn3.style.display = 'none';
                    rlogo.style.display = 'block';
                    userinfo.style.display = 'block';
                    dropbtn.style.display = 'inline-block';
                    if (window.localStorage.getItem('avatar')) {
                        document.querySelector('#rlogo img').src = window.localStorage.getItem('avatar');
                    }
                    document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + res.username;
                    if (res.avatar) {
                        document.querySelector('#rlogo img').src = res.avatar;
                    } else {
                        document.querySelector('#rlogo img').src = "img/register.png";
                    }
                    if (res.role == 'teacher') {
                        teacherlogo.style.display = 'block';
                        document.getElementById('rolelogo').innerHTML = '教师';
                    } else if (res.role == 'student') {
                        teacherlogo.style.display = 'none';
                        document.getElementById('rolelogo').innerHTML = '学生';
                    }
                })
        } else {
            console.log('cookie已注销');
            dropbtn.style.display = 'none';
        }
    }
    //封装每隔五分钟发送请求的函数
    function personBusi() {
        var cookie = JSON.parse(getCookie("init"));
        setTimeout(personBusi, 1000 * 60 * 5); //这里的1000表示1秒有1000毫秒,1分钟有60秒,5表示总共5分钟 
        axios({
                url: "/login",
                method: "post",
                data: {
                    "username": cookie.name,
                    "password": cookie.pass,
                }
            })
            .then(response => {
                if (response.data.code == 1) {
                    var res1 = response.data.data;
                    console.log('刷新token');
                    rlogo.style.display = 'block';
                    userinfo.style.display = 'block';
                    dropbtn.style.display = 'inline-block';
                    window.localStorage.removeItem("token");
                    window.localStorage.setItem("token", res1.token);
                    document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + res1.username;
                    if (res1.role == 'teacher') {
                        teacherlogo.style.display = 'block';
                        document.getElementById('rolelogo').innerHTML = '教师';
                    } else if (res1.role == 'student') {
                        teacherlogo.style.display = 'none';
                        document.getElementById('rolelogo').innerHTML = '学生';
                    }
                    if (res1.avatar) {
                        document.querySelector(".pic img").src = res1.avatar;
                    } else {
                        document.querySelector('#rlogo img').src = "img/register.png";
                    }
                }
            })

    }
    //验证token是否失效
    if (window.localStorage.getItem("token")) {
        axios({
            method: 'post',
            url: '/refresh',
        }).then(response => {
            var res = response.data;
            console.log(res);
            if (res.code == 1) {
                var id3 = window.localStorage.getItem('username');
                loginbtn1.style.display = 'none';
                loginbtn2.style.display = 'none';
                loginbtn3.style.display = 'none';
                userinfo.style.display = 'block';
                rlogo.style.display = 'block';
                dropbtn.style.display = 'inline-block';
                if (window.localStorage.getItem('avatar')) {
                    document.querySelector('#rlogo img').src = window.localStorage.getItem('avatar');
                } else {
                    document.querySelector('#rlogo img').src = "img/register.png";
                }
                document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + id3;
                var role3 = window.localStorage.getItem('role');
                if (role3 == 'teacher') {
                    teacherlogo.style.display = 'block';
                    document.getElementById('rolelogo').innerHTML = '教师';
                } else if (role3 == 'student') {
                    teacherlogo.style.display = 'none';
                    document.getElementById('rolelogo').innerHTML = '学生';
                }
                console.log('token有效');
            } else {
                console.log('error');
            }

        }).catch(err => {

        })
    }
    //登录

    var login = document.getElementById('submit');
    var username = document.getElementById('username');
    var password = document.getElementById('password');
    var role = '';
    var role1 = '';
    var token1 = '';
    var id1 = '';
    var avatar = '';

    login.addEventListener('click', function() {

            var un1 = username;
            var pw1 = password;
            axios({
                method: 'post',
                url: '/login',
                data: {
                    username: un1.value,
                    password: pw1.value,
                } //params是拼接参数请求，而data是把参数放进请求体
            }).then(response => {
                var res = response.data;
                console.log(res);
                if (res.code == 1) {
                    console.log('登录成功');
                    document.getElementById('userinfo').innerHTML = '用户' + '&nbsp' + res.data.username;
                    document.getElementById('loginbtn3').disabled = false;
                    loginbtn1.style.display = 'none';
                    loginbtn2.style.display = 'none';
                    loginbtn3.style.display = 'none';
                    rlogo.style.display = 'block';
                    userinfo.style.display = 'block';
                    logging.style.display = 'none';
                    mask.style.display = 'none';
                    dropbtn.style.display = 'inline-block';
                    window.localStorage.removeItem('username');
                    window.localStorage.removeItem('token');
                    window.localStorage.removeItem('role');
                    window.localStorage.removeItem('id');
                    window.localStorage.removeItem('avatar');
                    window.localStorage.removeItem('password');
                    console.log('欢迎' + res.data.username);
                    token1 = res.data.token;
                    id1 = res.data.id;
                    role = res.data.role;
                    if (res.data.role == 'teacher') {
                        teacherlogo.style.display = 'block';
                        document.getElementById('rolelogo').innerHTML = '教师';
                    } else if (res.data.role == 'student') {
                        teacherlogo.style.display = 'none';
                        document.getElementById('rolelogo').innerHTML = '学生';
                    }
                    if (res.data.avatar) {
                        avatar = res.data.avatar;
                        window.localStorage.setItem('avatar', avatar);
                        document.querySelector('#rlogo img').src = window.localStorage.getItem('avatar');
                    } else {
                        document.querySelector('#rlogo img').src = "img/register.png";
                    }
                    // console.log(token1);
                    if (token1) {
                        // window.localStorage.removeItem('token');
                        window.localStorage.setItem('token', token1);
                        window.localStorage.setItem('role', role);
                        window.localStorage.setItem('id', id1);
                        window.localStorage.setItem('username', un1.value);
                        window.localStorage.setItem('password', pw1.value);
                    }
                } else if (res.msg = '用户名或密码错误') {
                    document.getElementById('error').innerHTML = '用户名或密码错误';
                    setTimeout(() => {
                        document.getElementById('error').innerHTML = '';
                    }, 2000);
                    console.log('error');
                }

            })
        })
        //注册
    var register1 = document.querySelector('#register1');
    var username1 = document.querySelector('#username1');
    var password1 = document.querySelector('#password1');
    var teacher = document.querySelector('#teacher');
    var student = document.querySelector('#student');

    teacher.addEventListener('change', function() {
        if (this.checked) {
            role1 = 'teacher';
        }
    })
    student.addEventListener('change', function() {
        if (this.checked) {
            role1 = 'student';
        }
    })

    register1.addEventListener('click', function() {

            var un2 = username1;
            var pw2 = password1;
            axios({
                method: 'post',
                url: '/register',
                data: {
                    username: un2.value,
                    password: pw2.value,
                    role: role1
                } //params是拼接参数请求，而data是把参数放进请求体
            }).then(response => {
                var res = response.data;
                console.log(res);
                if (res.code == 1) {
                    console.log('注册成功');
                    document.getElementById('error1').innerHTML = '注册成功';
                } else if (res.msg = '该用户已经被注册过了') {
                    document.getElementById('error1').innerHTML = '该用户名已被使用';
                    setTimeout(() => {
                        document.getElementById('error1').innerHTML = '';
                        var u = document.getElementById('username1');
                        u.value = '';
                        var p = document.getElementById('password1');
                        p.value = '';
                    }, 2000)

                    console.log('error');
                }

            })
        })
        //七天免登录
        //设置cookie
    function setCookie(_name, val, expires) {
        var d = new Date();
        d.setDate(d.getDate() + expires);
        document.cookie = _name + "=" + val + ";path=/;expires=" + d.toGMTString();
    }

    //获取cookie
    function getCookie(_name) {
        var cookie = document.cookie;
        var arr = cookie.split("; ");
        for (var i = 0; i < arr.length; i++) {
            var newArr = arr[i].split("=");
            if (newArr[0] == _name) {
                return newArr[1];
            }
        }
    }
    /*
       如何将json对象转换为字符串
           JSON.stringify(对象);
           返回值是一个字符串
       如何将字符串转换为json对象
           JSON.parse(字符串)
           返回值是对象
    */
    //删除cookie
    var oBtn = document.getElementById("submit");
    var oUser = document.getElementById("username");
    var oPass = document.getElementById("password");
    var oCheck = document.getElementById("check1");

    if (getCookie("init")) {
        var cookie = JSON.parse(getCookie("init"));
        oUser.value = cookie.name;
        oPass.value = cookie.pass;
        oCheck.checked = true;
    }

    oBtn.onclick = function() {
        if (oCheck.checked) {
            var obj = {};
            obj.name = oUser.value;
            obj.pass = oPass.value;
            var str = JSON.stringify(obj);
            setCookie("init", str, 7);
        }
    }

    //退出登录的函数
    function Outlogin() {
        loginbtn1.style.display = 'block';
        loginbtn2.style.display = 'block';
        loginbtn3.style.display = 'block';
        rlogo.style.display = 'none';
        userinfo.style.display = 'none';
        teacherlogo.style.display = 'none';
        dropbtn.style.display = 'none';
        window.localStorage.removeItem("token");
        var obj = {};
        obj.name = '';
        obj.pass = '';
        var str = JSON.stringify(obj);
        setCookie("init", str, 0.000001);
    }

    //退出登录
    document.querySelector("#out-login").addEventListener('click', function() {
            Outlogin();
        })
        //搜索功能模块
    var search_input = $('.search-input');
    var search_content = $('.search-content');
    var search_box = $('.search');
    search_input.addEventListener('input', function() {
        var value = this.value.replace(/\s/g, '')
        if (value != '') {
            search(value);
        } else {
            clearTimeout(timer);
            $('.search-content').style.display = 'none';
            search_content.innerHTML = '';
        }
    })
    search_input.addEventListener('focus', function() {
        this.style.color = '#333'
    })
    search_input.addEventListener('blur', function() {
        this.style.color = '#999'
        setTimeout(() => {
            search_input.value = '';
        }, 1000);
    })
    search_box.addEventListener('click', function(e) {
        e.stopPropagation()
        var value = search_input.value.replace(/\s/g, '')
        if (value != '') {
            search_content.style.height = '320px';
            $('.search-content').style.display = 'block';
        }
    })
    document.addEventListener('click', function() {
        search_content.style.display = 'none';
    })
    var to_search = $('.to_search');
    to_search.addEventListener('click', function() {
        var value = search_input.value.replace(/\s/g, '');
        if (value != '') {
            window.localStorage.title = value;
            window.location.href = '../Searchcourse/searchcourse.html';
        }
    })
    window.addEventListener('keyup', function(e) {
            if (e.keyCode == 13 && search_input.value != '' && search_input == document.activeElement) {
                to_search.click()
            }
        })
        //利用防抖函数优化搜索课程功能
    var timer = null

    function search(value) {
        clearTimeout(timer)
        timer = setTimeout(function() {
            axios({
                url: '/course/search',
                params: {
                    title: value
                }
            }).then(response => {
                if (response.data.msg == '查找成功') {
                    var data = response.data.data
                    var str = ''
                    for (var k in data) {
                        str +=
                            `<li courseid="` + data[k].id + `">
                       <img src="` + data[k].image + `" alt="">
                       <div class="course-info">
                           <h2 class="course-title">` + data[k].title + `</h2>
                           <div class="teacher-info">
                               <span class="teacher-name">` + data[k].teacherName + `</span>
                               <span class="teacher-work">` + data[k].teacherTitle + `</span>
                           </div>
                       </div>
                   </li>`
                    }
                    search_content.innerHTML = str;
                    var course_titles = search_content.querySelectorAll('.course-title');
                    var course_titles_len = course_titles.length;
                    var teacher_names = document.querySelectorAll('.teacher-name');
                    var teacher_works = document.querySelectorAll('.teacher-work');
                    var reg = new RegExp(value, "g");
                    for (var i = 0; i < course_titles_len; i++) {
                        course_titles[i].innerHTML = course_titles[i].innerHTML.replace(reg, '<span class="highlight">' + value + '</span>')
                        teacher_names[i].innerHTML = teacher_names[i].innerHTML.replace(reg, '<span class="highlight">' + value + '</span>')
                        teacher_works[i].innerHTML = teacher_works[i].innerHTML.replace(reg, '<span class="highlight">' + value + '</span>')
                    }
                    $('.search-content').style.display = 'block';
                }
                console.log(response.data);
                var li1 = document.querySelectorAll('li');
                for (let t = 0; t < li1.length; t++) {
                    li1[t].addEventListener('click', function() {
                        window.localStorage.setItem('courseid', li1[t].getAttribute('courseid'));
                        Ifbuy();
                    })
                }
            }).catch(err => {
                console.log(err);
            })
            console.log(value)
        }, 800)
    }
    var item = document.getElementsByClassName("item");
    var it = item[0].getElementsByTagName("div");
    var content = document.getElementsByClassName("content");
    var con = content[0].getElementsByTagName("div");
    for (let i = 0; i < it.length; i++) {
        it[i].onclick = function() {
            for (let j = 0; j < it.length; j++) {
                it[j].className = '';
                con[j].style.display = "none";
            }
            this.className = "active";
            it[i].index = i;
            con[i].style.display = "block";
        }
    }
    var closebtn1 = $('.closebtn');
    var login = $('.logging');
    var link1 = $('#loginbtn1');
    var link2 = $('#loginbtn2');
    var link3 = $('#loginbtn3');
    var mask = $('.wrapper');

    link1.addEventListener('click', function() {
        login.style.display = 'block';
        mask.style.display = 'block';
        setTimeout(function() {
            login.style.opacity = 1;
        }, .1);

    })
    link2.addEventListener('click', function() {
        login.style.display = 'block';
        mask.style.display = 'block';
        setTimeout(function() {
            login.style.opacity = 1;
        }, .1);

    })
    link3.addEventListener('click', function() {
        login.style.display = 'block';
        mask.style.display = 'block';
        setTimeout(function() {
            login.style.opacity = 1;
        }, .1);

    })
    closebtn1.addEventListener('click', function() {
        mask.style.display = 'none';
        login.style.opacity = 0;
        login.style.display = 'none';
    })

    function successtip() {
        var tips = $('.aftertips');
        tips.style.opacity = '1';
        tips.style.top = '90px';
        tips.style.color = '#67c23a';
        console.log('成功');
        setTimeout(function() {
            tips.style.opacity = '.2';
            tips.style.top = '-60px';
        }, 1800)
    }
    //  操作失败后的提示信息
    function errtip() {
        var tips = $('.aftertips')
        tips.style.opacity = '1';
        tips.style.top = '90px';
        tips.style.color = '#f02019';
        setTimeout(function() {
            tips.style.opacity = '.2';
            tips.style.top = '-60px';
        }, 1800)
    }
    //滚动条事件小火箭平滑运行
    var obtn = $('.back-top'); //获取回到顶部按钮的ID
    var clientHeight = document.documentElement.clientHeight; //获取可视区域的高度
    var timer = null; //定义一个定时器
    var isTop = true; //定义一个布尔值，用于判断是否到达顶部

    window.onscroll = function() { //滚动条滚动事件

        //获取滚动条的滚动高度
        var osTop = document.documentElement.scrollTop || document.body.scrollTop;

        if (osTop >= clientHeight) { //如果滚动高度大于可视区域高度，则显示回到顶部按钮
            obtn.style.display = 'block';
        } else { //否则隐藏
            obtn.style.display = 'none';
        }

        //主要用于判断当 点击回到顶部按钮后 滚动条在回滚过程中，若手动滚动滚动条，则清除定时器
        if (!isTop) {
            clearInterval(timer);
        }
        isTop = false;
    }

    obtn.onclick = function() { //回到顶部按钮点击事件
        //设置一个定时器
        timer = setInterval(function() {
            //获取滚动条的滚动高度
            var osTop = document.documentElement.scrollTop || document.body.scrollTop;
            //用于设置速度差，产生缓动的效果
            var speed = Math.floor(-osTop / 6);
            document.documentElement.scrollTop = document.body.scrollTop = osTop + speed;
            isTop = true; //用于阻止滚动事件清除定时器
            if (osTop == 0) {
                clearInterval(timer);
            }
        }, 30);
    }
    Getdetailcontent();
    var more_content = document.querySelector('.more-content')
    var comment_section = document.querySelector('.comment-section')
    more_content.addEventListener('click', function() {
        if (this.querySelector('.more').innerHTML == '更多') {
            this.querySelector('.more').innerHTML = '收起';
            if (comment_section.children[1].lastChild) {
                comment_section.style.height = comment_section.children[1].lastChild.offsetTop - comment_section.offsetTop + 60 + 'px'
            }
        } else {
            this.querySelector('.more').innerHTML = '更多'
            comment_section.style.height = '150px';
        }
    })
    var course_comment = document.querySelector('.course-comment');
    axios({
        url: '/course/getComment',
        params: {
            courseId: window.localStorage.courseid
        }
    }).then(response => {
        var data = response.data.data
        console.log(data);
        var comment_title = document.querySelector('.comment-title')
        comment_title.children[0].innerHTML = data.length;
        if (response.data.msg == '获取成功' && data.length != 0) {
            var str = ''
            for (var k in data) {
                if (data[k].from_avatar) {
                    str +=
                        `<li class="user-comment">
                <img src="${data[k].from_avatar}" alt="" class="user-avatar"> 
                <div class="comment-info">
                <h3 class="comment-username">用户： ${data[k].from_name}</h3> 
                <p class="commment-content">留言： ${data[k].content}</p>
                </div>
            </li>`
                } else {
                    str +=
                        `<li class="user-comment">
                <img src="img/register.png" alt="" class="user-avatar"> 
                <div class="comment-info">
                    <h3 class="comment-username">用户： ${data[k].from_name}</h3> 
                    <p class="commment-content">留言： ${data[k].content}</p>
                </div>
            </li>`
                }
            }
            course_comment.innerHTML = str
        } else if (response.data.msg == '获取成功' && data.length == 0) {
            course_comment.innerHTML = ''
        } else {
            console.log(response);
        }
    }).catch(err => {
        console.log(err);
    })

    function Getdetailcontent() {
        axios({
            method: 'get',
            url: '/course/detail',
            params: {
                id: window.localStorage.getItem('courseid')
            }
        }).then(response => {
            var res = response.data.data;
            console.log(res);
            $('title').innerHTML = res.title;
            $('.ctitle').innerHTML = res.title;
            $('.image1').src = res.image;
            $('.shopname').innerHTML = '商品：' + res.title;
            $('.yuan1').innerHTML = '￥' + res.price;
            $('.yuan').innerHTML = '￥' + res.price;
            var num = '';
            var rightcontent = $('.top-right-container');
            var pricewrap = $('.price-wrap');
            var coursebottom = $('.part-bottom');
            var coursecontent = $('.course-content');
            var str1 = '';
            var str2 = '';
            var str3 = '';
            var str4 = '';
            str1 += `<div class="top-big-title">${res.title}</div>
            <div class="top-small-title">${res.brief}</div>`;
            if (res.subscription) {
                num = res.subscription.split('；')[0].split('，')[0].substring(6, 9).replace(' ', '');
                $('.menu-span').innerHTML = `/共${num}节`
                var str0 = res.subscription;
                var sarr = str0.substring(5, 11);
                var sarr1 = str0.substring(12, 19);
                console.log(sarr1);
                str1 += `<div class="top-items">
                <div class="top-item1">${res.pruchasedCount}</div>
                <div class="top-item2">${sarr}</div>
                <div class="top-item3">${sarr1}</div>
                <div style="clear:both;"></div>
            </div>`;
            }
            str1 += ` <div class="top-price">
                <div class="top-price-icon">￥</div>
                <div class="top-price-value">${res.price}</div>
            </div>
            <div class="top-btns">
                <div class="top-btn-one">加入学习</div>
                <div class="top-btn-two">
                    <div class="top-btn-two-attach">赚￥${res.price}.00</div>
                    <div class="top-btn-two-icon"></div>
                    <div class="top-btn-two-text">去分享</div>
                </div>
            </div>`;
            rightcontent.innerHTML = str1;
            str2 += `<div class="price-money">
            <div class="price-money-one">拉勾上新</div>
            <div class="price-money-two">￥</div>
            <div class="price-money-three">${res.price}</div>
        </div>
        <div class="price-btn">
            ￥${res.price} 加入学习
        </div> 
        <div class="test-button">
        <img src="./img/earphone.png" alt="" class="earphone">
        <div class="test-text">试听</div>
    </div>`;
            pricewrap.innerHTML = str2;
            str3 += '<h1>背景介绍</h1>';
            if (res.background) {
                var background = res.background.replace(/\n/g, '<br>')
                str3 += `<p class="bg">${background}</p>`;
            }
            str3 += '<h1>专栏解读</h1>';
            if (res.interpretation) {
                var interpretation = res.interpretation.replace(/\n/g, '<br>')
                str3 += `<p class="ss">${interpretation}</p>`;
            }
            str3 += `<h1 class="ti">讲师简介</h1> <p class="ctitle">${res.teacherName}  &nbsp${res.teacherTitle}</p>`;
            if (res.teacher_infomation && res.teacher_infomation != 'undefined') {
                var teacher_infomation = res.teacher_infomation.split('\n\n')[1]
                if (teacher_infomation == 'undefined' || !teacher_infomation) {
                    teacher_infomation = res.teacher_infomation.split('\n')[1]
                }
                str3 += `<p>${res.teacher_infomation}</p>`
            }

            str3 += `<h1 class="ch">课程大纲</h1>
            <p class=p-pic>
                <img src="${res.syllabus}" alt="">
            </p>`;
            str3 += '<h1>订阅须知</h1>';
            if (res.subscription) {
                var subscription = res.subscription.replace(/\n+/g, '<br>').replace('召唤客服>>>', '').replace(/\r+/g, '<br>')
                str3 += `
                <p>${subscription}<a class="zi2" href="https://jinshuju.net/f/ngEPnR">召唤客服&gt;&gt;&gt;</a></p>`
            }
            coursebottom.innerHTML = str3;
            var category_info1 = ''
            var category_info2 = ''
            for (var k in res.courseSectionList) {
                if (k == 0) {
                    category_info1 +=
                        `<div class="open-text">${res.courseSectionList[0].section_name}</div>`
                    for (var key in res.courseSectionList[0].lessonList) {
                        category_info1 += `<div class="try-course clearfix" lesson_id="${res.courseSectionList[0].lessonList[key].lesson_id}">
                     <div class="course-title">
                         <span>试看</span>${res.courseSectionList[0].lessonList[key].lesson_name}
                     </div> 
                     <div class="lesson-pause"></div> 
                     <div class="lesson-play"></div> 
                 </div>`
                    }
                } else if (k == 1) {
                    category_info1 += `<section class="model">
                    <h2>${res.courseSectionList[1].section_name}</h2>`
                    for (var i = 0; i < res.courseSectionList[1].lessonList.length; i++) {
                        if (i == 0) {
                            category_info1 +=
                                `<div class="try-course clearfix" lesson_id="${res.courseSectionList[1].lessonList[0].lesson_id}">
                                 <div class="course-title">
                                     <span>试看</span>${res.courseSectionList[1].lessonList[0].lesson_name }</div> 
                                 <div class="lesson-pause"></div> 
                                 <div class="lesson-play"></div> 
                             </div>`
                        } else {
                            category_info1 +=
                                `<div class="lock-course clearfix" lesson_id="${res.courseSectionList[1].lessonList[i].lesson_id}">
                             <div class="course-title">${res.courseSectionList[1].lessonList[i].lesson_name}</div> 
                             <div class="lesson-pause"></div> 
                             <div class="lesson-play"></div> 
                             <div class="lesson-lock"></div> 
                             </div>`
                        }
                    }
                } else {
                    category_info2 += `<section class="model">
                 <h2>${res.courseSectionList[k].section_name}</h2>`
                    for (var j = 0; j < res.courseSectionList[k].lessonList.length; j++) {
                        category_info2 += `<div class="lock-course clearfix" lesson_id="${res.courseSectionList[k].lessonList[j].lesson_id}">
                     <div class="course-title">${res.courseSectionList[k].lessonList[j].lesson_name}</div> 
                     <div class="lesson-pause"></div> 
                     <div class="lesson-play"></div> 
                     <div class="lesson-lock"></div> 
                     </div>`
                    }
                    category_info2 += `</section>`;
                }
            }
            category_info2 =
                `<div class="click-see">` +
                category_info2 +
                `</div>`
            var initial = coursecontent.innerHTML;
            var category_info3 =
                `<div class="show-more">
                     <p>全部课程 ▼</p><span></span>
                 </div>`
            coursecontent.innerHTML = initial + category_info1 + category_info2 + category_info3;
            var show_more = document.querySelector('.show-more')
            var click_see = document.querySelector('.click-see')
            click_see.style.display = 'none'
            show_more.addEventListener('click', function() {
                if (this.children[0].innerHTML == '全部课程 ▼') {
                    this.children[0].innerHTML = '收起 ▲ '
                    this.children[1].style.transform = 'rotate(-0deg)'
                    click_see.style.display = 'block'
                } else {
                    click_see.style.display = 'none'
                    this.children[0].innerHTML = '全部课程 ▼'
                    this.children[1].style.transform = 'rotate(-180deg)'
                }
            })
            var price_btn = $('.price-btn');
            var price_btn1 = $('.top-btn-one');
            price_btn.addEventListener('click', function() {
                mask1.style.display = 'block';
            })
            price_btn1.addEventListener('click', function() {
                mask1.style.display = 'block';
            })

        })
    }
    var buybtn = $('.confirm_btn');
    var backbtn = $('.cancel_btn');
    var mask1 = $('.wrapper1');
    buybtn.addEventListener('click', function() {
        axios({
            method: 'post',
            url: '/course/buyCourse',
            data: {
                userId: window.localStorage.getItem('id'),
                courseId: window.localStorage.getItem('courseid')
            }
        }).then(response => {
            var res = response.data;
            console.log(res);
            if (res.code == -1) {
                if (res.msg = '你的余额不足, 请先充值') {
                    $('.aftertips').innerHTML = '余额不足！';
                    errtip();
                } else if (res.msg == '你已经购买了该课程') {
                    $('.aftertips').innerHTML = '已购买！';
                    errtip();
                }
            } else {
                mask1.style.display = 'none';
                $('.aftertips').innerHTML = res.msg;
                successtip();
                setTimeout(() => {
                    $('.aftertips').innerHTML = '为您跳转中。。';
                    successtip();
                }, 1000)
                setTimeout(() => {
                    window.location.href = '../course-details/course-details-three.html';
                }, 2000)


            }
        })
    })
    backbtn.addEventListener('click', function() {
        mask1.style.display = 'none';
    })

    function Ifbuy() {
        axios({
            method: 'post',
            url: '/course/hasBuyCourse',
            data: {
                userId: window.localStorage.getItem('id'),
                courseId: window.localStorage.getItem('courseid')
            }
        }).then(res => {
            console.log(res.data);
            if (res.data.msg == '已经购买了该课程') {
                window.location.href = '../course-details/course-details-three.html';
            } else {
                window.location.assign('../course-details/course-details-two.html');
                console.log('1');
            }
        })
    }

}